const https = require("https");
const cheerio = require("cheerio");
const fs = require("fs");
let utils = require("./utils");

class Apis {
  constructor() {}

  // 异步获取网页信息
  async getWebPage(httpUrl, downLoadFile, dest) {
    try {
      const html = await this.fetchHtml(httpUrl);
      await utils.createDirAccordingToUrl(downLoadFile, dest);
      await this.saveToFile(downLoadFile, html);
      console.log("数据处理完成！");
    } catch (error) {
      console.error("发生错误:", error);
    }
  }

  // 获取 HTML 内容
  fetchHtml(url) {
    return new Promise((resolve, reject) => {
      let html = "";
      https.get(url, (res) => {
        res.on("data", (chunk) => {
          html += chunk;
        });
        res.on("end", () => {
          resolve(html);
        });
        res.on("error", (err) => {
          reject(err);
        });
      });
    });
  }

  // 保存 HTML 到文件
  saveToFile(filePath, content) {
    return new Promise((resolve, reject) => {
      fs.writeFile(filePath, content, (err) => {
        if (err) {
          reject(err);
        } else {
          console.log("HTML 文件保存成功");
          resolve();
        }
      });
    });
  }
}

module.exports = new Apis();
